package org.gd.hellojson.jackson;

import com.google.gson.Gson;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Serializable;

/**
 *
 * @version $Id: $
 */
public class JacksonWriteExample implements Serializable {

    private static OutLog out = new OutLog(System.out);
    private static final ClassLoader LOADER = JacksonWriteExample.class.getClassLoader();

    public static void main(String[] args) {
        try {
            Gson gson = new Gson();

            ObjectMapper mapper = new ObjectMapper();
            mapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);
            //mapper.writeValue(new File("user.json"), user);

            JacksonUser user = new JacksonUser();
            out.println("------------------------------");
            out.println(mapper.writeValueAsString(user));
            out.println("------------------------------");
            out.println(gson.toJson(new JacksonUser()));
            out.println("------------------------------");

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final class OutLog extends PrintStream {
        private OutputStream out;
        public OutLog(OutputStream out) {
            super(out);
            this.out = out;
        }

        public void println(Object x) {
            try {
                out.write(x.toString()
                        .replace("{", "{\n\t")
                        .replace(",", ",\n\t")
                        .replace("}", "\n}").getBytes());
                out.write("\n".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void println(String x) {
            try {
                out.write(x
                        .replace("{", "{\n\t")
                        .replace(",", ",\n\t")
                        .replace("}", "\n}").getBytes());
                out.write("\n".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
